﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Admin.Models.Stores;
using Urs.Data.Domain.Stores;
using Urs.Data.Domain.Configuration;
using Urs.Services.Stores;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Extensions;
using Urs.Framework.Kendoui;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class GoodsParameterController : BaseAdminController
    {
        #region Fields

        private readonly IGoodsParameterService _goodsParameterService;
        private readonly ILocalizationService _localizationService;
        private readonly IActivityLogService _activityLogService;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;
        #endregion Fields

        #region Constructors

        public GoodsParameterController(IGoodsParameterService goodsParameterService,
            ILocalizationService localizationService, IActivityLogService activityLogService,
            IPermissionService permissionService, AdminAreaSettings adminAreaSettings)
        {
            this._goodsParameterService = goodsParameterService;
            this._localizationService = localizationService;
            this._activityLogService = activityLogService;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
        }

        #endregion

        #region Utilites

        [NonAction]
        protected void PrepareGroupsModel(GoodsParameterModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            var groups = _goodsParameterService.GetAllParameterGroups();
            foreach (var group in groups)
            {
                model.Groups.Add(new SelectListItem()
                {
                    Text = group.Name,
                    Value = group.Id.ToString()
                });
            }
        }

        #endregion

        #region Specification groups

        public IActionResult Groups()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            return View();
        }

        [HttpPost]
        public IActionResult Groups(PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var parameterGroups = _goodsParameterService.GetParameterGroups(command.Page - 1, command.Limit);
            var result = new ResponseResult
            {
                data = parameterGroups.Select(x => x.ToModel<GoodsParameterGroupModel>()),
                count = parameterGroups.TotalCount
            };
            return Json(result);
        }

        //edit
        public IActionResult GroupEdit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();
            var model = new GoodsParameterGroupModel();
            var parameterGroup = _goodsParameterService.GetParameterGroupById(id);
            if (parameterGroup == null)
            {
                return View(model);
            }
            else
            {
                model = parameterGroup.ToModel<GoodsParameterGroupModel>();
            }
            return View(model);
        }
        [HttpPost]
        public IActionResult GroupEdit(GoodsParameterGroupModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var parameterGroup = _goodsParameterService.GetParameterGroupById(model.Id);
            if (parameterGroup == null)
            {
                parameterGroup = new GoodsParameterGroup()
                {
                    Name = model.Name
                };
                _goodsParameterService.InsertParameterGroup(parameterGroup);
                //activity log
                _activityLogService.InsertActivity("AddNewSpecGroup", _localizationService.GetResource("ActivityLog.AddNewSpecGroup"), parameterGroup.Name);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    parameterGroup = model.ToEntity(parameterGroup);
                    _goodsParameterService.UpdateParameterGroup(parameterGroup);

                    //activity log
                    _activityLogService.InsertActivity("EditSpecGroup", _localizationService.GetResource("ActivityLog.EditSpecGroup"), parameterGroup.Name);
                }
            }
            //If we got this far, something failed, redisplay form
            return Json(new { success = 1 });
        }
        //delete
        [HttpPost]
        public IActionResult GroupDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var parameterGroup = _goodsParameterService.GetParameterGroupById(id);
            if (parameterGroup == null)
                return Json(new { error = 1 });

            parameterGroup.Deleted = true;
            _goodsParameterService.UpdateParameterGroup(parameterGroup);

            //activity log
            _activityLogService.InsertActivity("DeleteSpecGroup", _localizationService.GetResource("ActivityLog.DeleteSpecGroup"), parameterGroup.Name);

            return Json(new { success = 1 });
        }

        #endregion

        #region parameter

        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var model = new GoodsParameterListModel();

            //categories
            model.AvailableGroups.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" });
            foreach (var c in _goodsParameterService.GetAllParameterGroups())
                model.AvailableGroups.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() });

            return View(model);
        }

        [HttpPost]
        public IActionResult ListJson(PageRequest command, GoodsParameterListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var goodsParameters = _goodsParameterService.GetGoodsParameters(model.Name, model.ParameterGroupId, command.Page - 1, command.Limit);
            var result = new ResponseResult
            {
                data = goodsParameters.Select(x => x.ToModel<GoodsParameterModel>()),
                count = goodsParameters.TotalCount
            };
            return Json(result);
        }

        public IActionResult Search(string name)
        {
            var specAttributes = _goodsParameterService.GetGoodsParameterList(name);

            var list = new List<GoodsParameterModel>();

            foreach (var item in specAttributes)
            {
                if (!item.Deleted)
                    list.Add(new GoodsParameterModel() { Id = item.Id, Name = item.Name });
            }

            return Json(new { data = list });
        }

        //edit
        public IActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();
            var model = new GoodsParameterModel();
            PrepareGroupsModel(model);
            var goodsParameter = _goodsParameterService.GetGoodsParameterById(id);
            if (goodsParameter == null)
                return View(model);
            else
                model = goodsParameter.ToModel<GoodsParameterModel>();

            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(GoodsParameterModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var goodsParameter = _goodsParameterService.GetGoodsParameterById(model.Id);
            if (goodsParameter == null)
            {
                goodsParameter = new GoodsParameter()
                {
                    Name = model.Name,
                    GoodsParameterGroupId = model.ParameterGroupId
                };
                _goodsParameterService.InsertGoodsParameter(goodsParameter);
                //activity log
                _activityLogService.InsertActivity("AddNewSpecAttribute", _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), goodsParameter.Name);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    goodsParameter = model.ToEntity(goodsParameter);
                    _goodsParameterService.UpdateGoodsParameter(goodsParameter);

                    //activity log
                    _activityLogService.InsertActivity("EditSpecAttribute", _localizationService.GetResource("ActivityLog.EditSpecAttribute"), goodsParameter.Name);
                }
            }
            //If we got this far, something failed, redisplay form
            //return View(model);
            return Json(new { success = 1, data = new { Id = goodsParameter.Id, Name = goodsParameter.Name } });
        }

        //delete
        [HttpPost]
        public IActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var goodsParameter = _goodsParameterService.GetGoodsParameterById(id);
            if (goodsParameter == null)
                return Json(new { error = 1 });

            goodsParameter.Deleted = true;
            _goodsParameterService.UpdateGoodsParameter(goodsParameter);

            //activity log
            _activityLogService.InsertActivity("DeleteSpecAttribute", _localizationService.GetResource("ActivityLog.DeleteSpecAttribute"), goodsParameter.Name);

            return Json(new { success = 1 });
        }


        public IActionResult OptionList(int Id)
        {
            ViewBag.goodsParameterId = Id;
            return View();
        }

        //list
        [HttpPost]
        public IActionResult OptionList(int goodsParameterId, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var options = _goodsParameterService.GetGoodsParameterOptionsByGoodsParameter(goodsParameterId);
            var result = new ResponseResult
            {
                data = options.Select(x =>
                    {
                        var model = x.ToModel<GoodsParameterOptionModel>();
                        return model;
                    }),
                count = options.Count()
            };
            return Json(result);
        }

        //edit
        public IActionResult OptionEdit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var model = new GoodsParameterOptionModel();
            var sao = _goodsParameterService.GetGoodsParameterOptionById(id);
            if (sao != null)
                model = sao.ToModel<GoodsParameterOptionModel>();

            return View(model);
        }

        [HttpPost]
        public IActionResult OptionEdit(GoodsParameterOptionModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var sao = _goodsParameterService.GetGoodsParameterOptionById(model.Id);
            if (sao == null)
            {
                sao = new GoodsParameterOption()
                {
                    GoodsParameterId = model.GoodsParameterId,
                    Name = model.Name
                };
                _goodsParameterService.InsertGoodsParameterOption(sao);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    sao = model.ToEntity(sao);
                    _goodsParameterService.UpdateGoodsParameterOption(sao);

                }
            }
            return Json(new { success = 1, data = new { Id = sao.Id, Name = sao.Name, GoodsParameterId = sao.GoodsParameterId } });
        }

        //delete
        [HttpPost]
        public IActionResult OptionDelete(int Id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSpecAttributes))
                return HttpUnauthorized();

            var sao = _goodsParameterService.GetGoodsParameterOptionById(Id);
            if (sao == null)
                return Json(new { error = 1 });

            sao.Deleted = true;
            _goodsParameterService.UpdateGoodsParameterOption(sao);

            return Json(new { success = 1 });
        }

        #endregion
    }
}
